<?php

namespace app\modules\admin\controllers;

use app\models\ActiveMqApi;
use app\models\Outbound;

use app\models\Storage;
use app\models\Outlist;
use app\models\Order;
use app\models\User;
use app\models\Agent;
use app\models\Api;
use app\models\Card;
use app\models\OrderForm;
use app\models\CardDispatchForm;
use app\models\CardImportForm;
use app\models\CardSetPackageForm;
use app\models\CardSetTermForm;
use app\models\Isp;
use app\models\KeyMap;
use app\models\ManagerLog;
use app\models\Package;
use app\models\AgentPackage;
use app\models\UserPackage;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use Yii;
use yii\base\InvalidConfigException;
use yii\data\Pagination;
use yii\db\Expression;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\web\BadRequestHttpException;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;
use app\models\UploadForm;
use yii\web\UploadedFile;
use yii\helpers\Inflector;
use yii\helpers\FileHelper;
error_reporting(0);
/**
 * 出库管理
 * Class OutstorageController
 * @package app\modules\admin\controllers
 */
class OutboundController extends BaseController
{
    /**
     * 出库单列表
     * @return string
     * @throws ForbiddenHttpException
     */
    public function actionList()
    {

        $query = Outbound::find()->alias("outbound");
        if (!empty($this->get('orderno'))) {
            /** @var Agent $searchOrderno */
            $query->andWhere(['like','orderno' , $this->get('orderno')]);
        }

        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('id DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $list = $query->all();
        //pr($list);
        return $this->render('list', [
            'list' => $list,
            'pagination' => $pagination,
        ]);
    }
    /**
     * 出库单添加
     * @return string
     * @throws ForbiddenHttpException
     */
    public function actionEdit()
    {

        $orderedit = new Outbound();
        $aa = Yii::$app->request->post("Outbound","order_id");
        $id = $aa['order_id'];
        $order = Order::find()->where(['id' => $id])->one();
        $orderedit->batch_no = Order::generateBatchNo($this->manager->id);
        $orderedit->out_order = date('Ymd').time();
        $orderedit->isp_id = $order->isp_id;
        $orderedit->package_id = $order->package_id;
        $orderedit->number = $order->number;

        $orderedit->price = $order->price;
        $orderedit->orderno = $order->orderno;
        $orderedit->total_price = $order->amount;
        $orderedit->create_time = time();
        $orderedit->title = $order->titles;
        if ($orderedit->load($this->post())){
            $ischeck = Outbound::checkIccid($aa['iccid_start'],$aa['iccid_end'],$aa['iccid_list'],$order->uid,$order->agent,$order->package_id,$order->term_length,$order->term_length_unit,$order->number,$order->amount);
            if($ischeck['code'] =='1001'){
                throw new ForbiddenHttpException($ischeck['msg']);
            }
        }


        if ($orderedit->load($this->post()) && $orderedit->save()) {


            ManagerLog::info($this->manager->id, '操作完成', print_r($orderedit->attributes, true));
            Yii::$app->db->createCommand()->update('order', ['status' => 1], 'id = :id',['id' => $id])->execute();
            Yii::$app->session->addFlash('success', '数据已保存。');
            Yii::$app->session->setFlash('redirect', json_encode([
                'url' => Url::to(['outbound/list']),
                'txt' => '订单'
            ]));
        }
        //pr($orderedit,0);
        return $this->render('edit',[
            'orderedit' => $orderedit,
        ]);
    }
    /**
     * 出库单修改
     * @return string
     * @throws ForbiddenHttpException
     */
    public function actionModify(){
        $id = $this->get('id');
        $modify = Outbound::findOne(['id' => $id]);
        //echo $modify->order_id;

        if ($modify->load($this->post()) && $modify->save()) {
            ManagerLog::info($this->manager->id, '保存入库订单', print_r($modify->attributes, true));
            Yii::$app->session->addFlash('success', '数据已保存。');
            Yii::$app->session->setFlash('redirect', json_encode([
                'url' => Url::to(['/admin/outbound/list']),
                'txt' => '入库订单列表'
            ]));
        }
        return $this->render('modify',[
            'orderedit' => $modify,
        ]);
    }
    /**
     * 订单列表
     * @return string
     * @throws ForbiddenHttpException
     */
    public function actionOrderList()
    {
        if (!$this->manager->can('outbound/menu')) {
            throw new ForbiddenHttpException('没有权限。');
        }

        $query = Order::find()->alias("order");
        if (!empty($this->get('orderno'))) {
            /** @var Agent $searchOrderno */
            $query->andWhere(['like','orderno' , $this->get('orderno')]);
        }
        $pagination = new Pagination(['totalCount' => $query->count(), 'pageSize' => 20]);
        $query->orderBy('id DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $orderList = $query->all();

        //pr($orderList);
        foreach($orderList as $key => $val){
            //echo "agent:".$orderList[$key]->agent;echo "<br>";
            if(empty($orderList[$key]->agent)){
                $orderList[$key]->username = OrderForm::nameget("user",$orderList[$key]->uid);
                //echo "uname:".OrderForm::nameget("user",$orderList[$key]->uid);echo "<br>";
            }else{
                $orderList[$key]->agentname = OrderForm::nameget("agent",$orderList[$key]->agent);
                //echo "agent:".OrderForm::nameget("agent",$orderList[$key]->agent);echo "<br>";
            }
        }

        //pr($orderList);
        return $this->render('order_list', [
            'orderList' => $orderList,
            'pagination' => $pagination,
        ]);
    }
    /**
     * 添加修改订单
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionOrderEdit()
    {
        if (!$this->manager->can('outbound/menu')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $id = $this->get('id');
        $model = new OrderForm();
        $model->setAttributes($this->get());

        if (!empty($id)) {
            $order = Order::findOne(['id' => $id]);
            $order->create_time = time();
            if (empty($order)) {
                throw new NotFoundHttpException('没有找到卡信息。');
            }
            if(!empty($order->agent)){
                $model->user_type='agent';
                $order->uid="";
                $model->username = OrderForm::nameget("agent",$order->agent);
            }else{
                $model->user_type='user';
                $order->agent="";
                $model->username = OrderForm::nameget("user",$order->uid);
            }
        } else {
            $order = new Order();
            $order->create_time = time();
            $order->orderno = Outbound::generateBatchNo();
        }
        $orderForm = Yii::$app->request->post("OrderForm");
        $uid = OrderForm::useridget($orderForm['user_type'],$orderForm['username']);
        if($orderForm['user_type']=='user'){
            $order->uid = $uid;
            $order->agent="";
        }else{
            $order->agent = $uid;
            $order->uid = "";
        }
        $modela = new UploadForm();
        if (Yii::$app->request->isPost) {
            $modela->file = UploadedFile::getInstance($modela, 'file');
            if (!empty($modela->file)) {
                $dir = 'cert';
                $relative_path = $dir . '/' . date('y/m/');
                $real_path = Yii::$app->params['upload_path'] . $relative_path;
                if (!file_exists($real_path)
                    && !FileHelper::createDirectory($real_path)) {
                    throw new Exception('无法创建目录。');
                }
                $file_name = substr(uniqid(md5(rand()), true), 0, 10);
                $file_name .= '-' . Inflector::slug($modela->file->baseName);
                $file_name .= '.' . $modela->file->extension;
                $uri = $relative_path . $file_name;
                if (!$modela->file->saveAs($real_path . $file_name)) {
                    Yii::error('无法保存上传文件：' . print_r($modela->file->error, true));
                    throw new Exception('无法保存上传文件。');
                }
                $order->file = $uri;
            }
        }
        $imgurl = \Yii::$app->urlManager->hostInfo."/uploads/".$order->file;
        $order->status = 0;
        //print_r($model);
        //if ($order->load($this->post())  && $model->dispatch() && $order->save() ) {
        if ($order->load($this->post()) && $order->save() ) {
            ManagerLog::info($this->manager->id, '保存卡', print_r($order->attributes, true));
            $id = $order->attributes['id'];
            Yii::$app->db->createCommand()->update('order', ['amount' => $order->amount*$order->term_length], 'id = :id',['id' => $id])->execute();
            Yii::$app->session->addFlash('success', '数据已保存。');
            Yii::$app->session->setFlash('redirect', json_encode([
                'url' => Url::to(['/admin/outbound/order-list']),
                'txt' => '订单列表'
            ]));
        }
        return $this->render('order_edit', [
            'order' => $order,
            'model' => $model,
            'modela' => $modela,
            'imgurl' => $imgurl,
        ]);
    }
    /**
     * 删除订单
     * @return array
     */
    public function actionOrderDelete(){
        $id = $this->get('id');
        $model = Order::findOne(['id' => $id]);
        if(empty($model)){
            return [
                'message'=>'没有找到日志信息'
            ];
        }
        try {
            $model->delete();
        } catch (\Throwable $e){
        }
        ManagerLog::info($this->manager->id,'删除订单',print_r($model->attributes,true));
        return [
            'result'=>'success'
        ];
    }
    public function actionPackageprice()
    {

        $id = $this->get('id');//套餐id
        $usertype = $this->get('usertype');//用户类型
        $username = $this->get('username');//用户名称
        if($usertype=='user'){
            //用户
            $List = User::find()
                ->andWhere(['username' => $username])
                ->andWhere(['status' => User::STATUS_OK])
                ->one();
            $packageList = UserPackage::findOne(['uid' => $List->id, 'package_id' => $id]);
            if(empty($packageList) || ($packageList->cost_price<=0)){
                return [
                    'code'=>'1001',
                    'msg'=>'此用户未设置价格',
                    'data'=>''
                ];
                exit;
            }
            $model['sale_price']=$packageList->cost_price;
        }else{
            //代理商
            $List = Agent::find()
                ->andWhere(['username' => $username])
                ->andWhere(['status' => Agent::STATUS_OK])
                ->one();
            $packageList = AgentPackage::findOne(['agent_id' => $List->id, 'package_id' => $id]);
            if(empty($packageList) || ($packageList->cost_price<=0)){
                return [
                    'code'=>'1002',
                    'msg'=>'此代理商未设置价格',
                    'data'=>''
                ];
                exit;
            }
            $model['sale_price']=$packageList->cost_price;
        }

        //echo $packageList->sale_price;exit;
        /*
        pr($packageList);
        //echo $id;exit;
        $model = Package::findOne(['id' => $id])->toArray();*/
        //$modelarr=json_encode($model);
        return [
            'code'=>'1',
            'msg'=>'返回成功',
            'data'=>$model
        ];

    }
    public function actionIspList()
    {
        /*if (!$this->manager->can('card/isp')) {
            throw new ForbiddenHttpException('没有权限。');
        }*/
        $query = Isp::find();
        $query->andWhere(['status' => Isp::STATUS_OK]);
        $pagination = new Pagination(['totalCount' => $query->count()]);
        echo "<pre>";
        print_r($pagination);exit;
        $query->offset($pagination->offset)->limit($pagination->limit);
        $query->orderBy('id DESC');
        $ispList = $query->all();
        echo "<pre>";
        print_r($ispList);exit;
        return $this->render('isp_list', [
            'ispList' => $ispList,
            'pagination' => $pagination,
        ]);
    }

}
